from flask_mail import Message
from app import mail
from flask import render_template
from app import app
from threading import Thread

# 使用线程时，需要牢记Flask的一个重要设计方面。 
# Flask使用上下文来避免必须跨函数传递参数。
# msg参数会被发送到线程, 
def send_async_email(app, msg):
    # 开启 flask应用上下文
    with app.app_context():
        mail.send(msg)


def send_email(subject, sender, recipients, text_body, html_body):
    msg = Message(subject, sender=sender, recipients=recipients)
    msg.body =  text_body
    msg.html = html_body
    # mail.send(msg)
    # 电子邮件的发送将在线程中运行，并且当进程完成时，线程将结束并自行清理
    Thread(target=send_async_email, args=(app, msg)).start()

# 发送密码重置电子邮件
def send_password_reset_email(user):
    token = user.get_reset_password_token()
    send_email('[Microblog] Reset Your Password',
               sender=app.config['ADMINS'][0],
               recipients=[user.email],
               text_body=render_template('email/reset_password.txt',
                                         user=user, token=token),
               html_body=render_template('email/reset_password.html',
                                         user=user, token=token))